package com.smart_campus.bus.controller;


import com.smart_campus.bus.domain.Journal;
import com.smart_campus.bus.service.JournalService;
import com.smart_campus.bus.vo.CommentVo;
import com.smart_campus.sys.common.DataGridView;
import com.smart_campus.bus.domain.Comment;
import com.smart_campus.bus.service.CommentService;
import com.smart_campus.sys.common.ResultObj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private JournalService journalService;


    /**
     * 查询全部评论
     * */
    @RequestMapping("selcomment")
    public DataGridView selComment(CommentVo commentVo){
        return commentService.selComment(commentVo);
    }


    /**
     * 根据文章id查询
     * */
    @RequestMapping("selbyjid")
    public DataGridView selbyjid(int jid){
        //根据文章id查询评论
        List<CommentVo> list1 = commentService.selCommentByJournalId(jid);
        System.out.println(list1.size());
        for(int i=0;i<list1.size();i++){
            int id = list1.get(i).getId();
            List<Comment> list = commentService.selbyid(id);
            list1.get(i).setData(list);
        }
        return new DataGridView(list1);
    }


    /**
     * 删除评论
     * */
    @RequestMapping("delcomment")
    public ResultObj delcomment(Integer id[]){
        try {
            for (Integer i:id){
                commentService.delCommentById(i);
            }
            return ResultObj.DELETE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }


    /**
     * 写评论
     * */
    @RequestMapping("writeComment")
    public Comment writeComment(Comment comment){
        /**
         * 评论时文章里评论加1
         * */
        Journal journal = journalService.getDataById(comment.getJournalId());
        journal.setCommentCount(journal.getCommentCount()+1);
        journalService.addCommentCount(journal);
        comment.setCreateTime(new Date());
        if (comment.getPid()!=null){
            return commentService.writeComment(comment);
        }else {
            comment.setPid(0);
        }
        return commentService.writeComment(comment);
    }

}